package com.xjgc.rest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.thoughtworks.xstream.core.JVM;
import com.xjgc.msibase.entity.MsiServerRecord;
import com.xjgc.msibase.entity.MsiServerRecordInfo;
import com.xjgc.msibase.service.IMsiServerRecordInfoService;
import com.xjgc.webservice.XParam;
import com.xjgc.webservice.XmlUtils;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.SpringContextUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: 小逗号
 * @date: 2023-11-28
 * @description:
 * @since:
 */
@Slf4j
public class JsonUtils {

    private static IMsiServerRecordInfoService msiServerRecordInfoService;

    private static IMsiServerRecordInfoService getRecordInfoService() {
        if (msiServerRecordInfoService == null) {
            msiServerRecordInfoService = SpringContextUtils.getBean(IMsiServerRecordInfoService.class);
        }
        return msiServerRecordInfoService;
    }

    private final static Map<String, Class> CLASS_MAP = new HashMap<>(16);

    public static Class getClass(String className) {
        if (!CLASS_MAP.containsKey(className)) {
            Class aClass = JVM.loadClassForName(className);
            CLASS_MAP.put(className, aClass);
        }
        return CLASS_MAP.get(className);
    }

    private static String jsonToXml(String jsonText, String className) {
        long start = System.currentTimeMillis();
        Class<XParam> aClass = JsonUtils.getClass(className);
        JSONObject jsonObject = JSON.parseObject(jsonText);
        Object jParam = JSON.toJavaObject(jsonObject, aClass);
        String xml = XmlUtils.toXml(jParam);
        long end = System.currentTimeMillis();
        log.info("Json转Xml{}耗时:{} ms", aClass.getSimpleName(), (end - start));
        return xml;
    }

    public static String toXml(MsiServerRecord record, String className) {

        String xml = jsonToXml(record.getRequestText(), className);
        getRecordInfoService().add(record.getId(), new Date(), MsiServerRecordInfo.Node.TO_XML, null, xml);
        return xml;
    }

}
